package com.lzy.elasticsearch.template;

import com.lzy.elasticsearch.service.ElasticsearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.function.Supplier;

@Slf4j
// TODO 看看这个方式可以注入ElasticsearchService实例不
public class ElasticsearchServiceTemplate {

    @Autowired
    private ElasticsearchService elasticsearchService;

    private final static int RETRY_COUNT = 3;

    public boolean existsIndex(GetIndexRequest request) {
        return apply(() ->elasticsearchService.existsIndex(request));
    }

    public BulkResponse bulk(BulkRequest request) {
        return null;
    }


    private <R> R apply(Supplier<R> sup) {
        try {
            return sup.get();
        } catch (Exception e) {
            Exception e2 = null;
            for (int i = 1; i < RETRY_COUNT; i++) {
                log.info("重试-->{}", i);
                try {
                    return sup.get();
                } catch (Exception e1) {
                    e2 = e1;
                }
            }
            throw new RuntimeException(e2);
        }
    }
}
